package com.changgou.util;

import com.changgou.file.FastDFSFile;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.*;

/**
 * 实现FastDFS文件管理!
 * 文件上传
 * 文件删除
 * 文件下载
 * 文件信息获取
 * Storage信息获取
 * Tracker信息获取
 */
public class FastDFSUtils {

    /**
     * 加载Tracker链接信息
     */
    static{
       try {
           // 查找classPath下的文件路径
           String fileName = new ClassPathResource("fdfs_client.conf").getPath();
           //加载Tracker链接信息
           ClientGlobal.init(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     * @param fastDFSFile
     * @throws Exception
     * @return
     */
    public static String[] upLoad(FastDFSFile fastDFSFile) throws Exception {
        //获取Tracker
        TrackerServer trackerServer = getTrackerServer();
        //通过Tracker的连接信息获取storage的连接信息，创建StroageClient存储连接信息
        StorageClient storageClient = new StorageClient(trackerServer,null);
        //创建StorageClient访问storage,实现文件上传，并且获取文件上传后的信息
        /**
         * 1:上传文件的字节数组
         * 2:文件的扩展名jpg
         * 3:附加参数比如:拍摄地址:北京
         */
        //附加参数
        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0]=new NameValuePair("author",fastDFSFile.getAuthor());
        /**
         * uploadFile[]
         *      uploadFile[O]:文件上传所存储的Storage的组名字    groupl
         *      uploadFile[1]:文件存储到Storage上的文件名字     MO0/02/44/itheima.jpg
         */
        String[] uploadFile = storageClient.upload_file(fastDFSFile.getContent(), fastDFSFile.getExt(), meta_list);
        return uploadFile;
    }

    /**
     * 获取文件信息
     * @return
     * @param groupName :文件的组名  changgou
     * @param remoteFi1eName :文件的存储路径名字  M00/00/00/rBWPil9m-ruAUBMuAAFhvc-3u5k128.jpg
     */
    public static FileInfo getFileInfo(String groupName, String remoteFi1eName) throws Exception {
        //获取Tracker
        TrackerServer trackerServer = getTrackerServer();
        //通过Tracker的连接信息获取storage的连接信息，创建StroageClient存储连接信息
        StorageClient storageClient = new StorageClient(trackerServer,null);
        //创建StorageClient获取文件上传后的信息
        FileInfo file_info = storageClient.get_file_info(groupName, remoteFi1eName);
        return file_info;
    }

    /**
     * 文件下载
     * @param groupName :文件的组名  changgou
     * @param remoteFi1eName :文件的存储路径名字  M00/00/00/rBWPil9m-ruAUBMuAAFhvc-3u5k128.jpg
     */
    public static InputStream downLoad(String groupName, String remoteFi1eName) throws Exception {
        //获取Tracker
        TrackerServer trackerServer = getTrackerServer();
        //通过Tracker的连接信息获取storage的连接信息，创建StroageClient存储连接信息
        StorageClient storageClient = new StorageClient(trackerServer,null);
        //下载文件
        byte[] download_file = storageClient.download_file(groupName, remoteFi1eName);
        //转为字节输入流
        return new ByteArrayInputStream(download_file);
    }

    /**
     * 文件删除
     * @param groupName :文件的组名  changgou
     * @param remoteFi1eName :文件的存储路径名字  M00/00/00/rBWPil9m-ruAUBMuAAFhvc-3u5k128.jpg
     */
    public static void deleteFile(String groupName, String remoteFi1eName) throws Exception {
        //创建Tracker客户端对象TrackerClient
        TrackerClient trackerClient = new TrackerClient();
        //通过Tracker客户端访问TrackerService服务，获取连接信息
        TrackerServer trackerServer = trackerClient.getConnection();
        //通过Tracker的连接信息获取storage的连接信息，创建StroageClient存储连接信息
        StorageClient storageClient = new StorageClient(trackerServer,null);
        //删除文件
        storageClient.delete_file(groupName, remoteFi1eName);
    }


    /**
     * 获取Storage的信息
     * @return
     * @throws IOException
     */
    public static StorageServer getStorage() throws IOException {
        //创建Tracker客户端对象TrackerClient
        TrackerClient trackerClient = new TrackerClient();
        //通过Tracker客户端访问TrackerService服务，获取连接信息
        TrackerServer trackerServer = trackerClient.getConnection();
        //获取storage信息
        return trackerClient.getStoreStorage(trackerServer);
    }

    /***
     * 获取Storage信息,IP和端口
     * @param groupName
     * @param remoteFileName
     * @return
     * @throws IOException
     */
    public static ServerInfo[] getFetchStorages(String groupName, String remoteFileName) throws IOException {
        //创建Tracker客户端对象TrackerClient
        TrackerClient trackerClient = new TrackerClient();
        //通过Tracker客户端访问TrackerService服务，获取连接信息
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
    }

    public static String getTrackerInfo() throws Exception {
        //获取Tracker
        TrackerServer trackerServer = getTrackerServer();
        //获取Tracker的IP，Http端口
        int tracker_http_port = ClientGlobal.getG_tracker_http_port();
        String ip = trackerServer.getInetSocketAddress().getHostString();
        String url = "http://"+ip+":"+tracker_http_port;
        return url;
    }

    public static ServerInfo[] getFetchTracker(String groupName, String remoteFileName) throws IOException {
        //创建Tracker客户端对象TrackerClient
        TrackerClient trackerClient = new TrackerClient();
        //通过Tracker客户端访问TrackerService服务，获取连接信息
        TrackerServer trackerServer = trackerClient.getConnection();
        //获取Tracker的IP，Http端口
        return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
    }

    /**
     * 获取Tracker
     * @return
     * @throws Exception
     */
    public static TrackerServer getTrackerServer() throws Exception{
        //创建Tracker客户端对象TrackerClient
        TrackerClient trackerClient = new TrackerClient();
        //通过Tracker客户端访问TrackerService服务，获取连接信息
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerServer;
    }

    public static void main(String[] args) throws Exception {
//        获取文件信息
/*        FileInfo fileInfo = getFileInfo("changgou", "M00/00/00/rBWPil9nB4aAQbR7AAFhvc-3u5k866.jpg");
        System.out.println(fileInfo.getSourceIpAddr());
        System.out.println(fileInfo.getCreateTimestamp());
        System.out.println(fileInfo.getFileSize());
        System.out.println(fileInfo.getCrc32());*/

/*      文件下载
        InputStream downLoad = downLoad("changgou", "M00/00/00/rBWPil9nB4aAQbR7AAFhvc-3u5k866.jpg");

        // 将文件写入本地磁盘
        FileOutputStream outputStream = new FileOutputStream("D:/2.jpg");

        //定义一个缓冲区
        byte[] buffer = new byte[1024];
        while (downLoad.read(buffer) != -1){
            outputStream.write(buffer);
        }
        outputStream.flush();
        outputStream.close();
        downLoad.close();
        */

/*        删除文件
        deleteFile("changgou", "M00/00/00/rBWPil9nB4aAQbR7AAFhvc-3u5k866.jpg");*/

        /*获取Storage信息
        StorageServer storageServer = getStorage();
        System.out.println(storageServer.getInetSocketAddress().getHostString()); // ip信息
        System.out.println(storageServer.getSocket()); //端口信息
        System.out.println(storageServer.getStorePathIndex()); //组信息
*/

        /*获取Storage信息,IP和端口
        ServerInfo[] fetchStorages = getFetchStorages("changgou", "M00/00/00/rBWPil9nCtiAWSIRAAFhvc-3u5k423.jpg");
        for (ServerInfo fetchStorage : fetchStorages) {
            System.out.println(fetchStorage.getIpAddr());
            System.out.println(fetchStorage.getPort());
        }
        */

//        System.out.println(getTrackerInfo());


    }

}
